<template>
  <div id="addTrainBox">
    <el-container style="height:100%">
      <el-header style="height:100px">
        <el-row class="end" style="width:95%;margin-top:25px">
          <el-button type="primary" size="mini" @click="saveAll">保存</el-button>
          <el-button type="primary" plain size="mini" @click="submitAll">提交</el-button>
        </el-row>
        <div class="imgCol">
          <div style="width:95%">
            <el-divider></el-divider>
          </div>
        </div>
      </el-header>
      <el-main>
        <!-- <component v-bind:is="which" v-on:keepSelection="keepStep($event)" v-bind:title="title"></component> -->
        <!-- <addTrainStep1 v-show="step" v-on:keepSelection="keepStep1($event)" v-bind:selection="selection"></addTrainStep1>
        <addTrainStep2 v-show="!step" v-on:keepSelection="keepStep2($event)"  v-bind:fatherForm="fatherForm"></addTrainStep2>-->
        <div>
          <el-steps :active="activeStep" align-center>
            <el-step title="选择培训课次"></el-step>
            <el-step title="录入详细信息"></el-step>
          </el-steps>
        </div>

        <div v-if="activeStep==1">
          <el-row style="margin-top:20px">
            <el-alert :closable="false" center title="选择课次" type="info"></el-alert>
          </el-row>
          <div class="imgCol" style="height:500px">
            <el-form
              :model="step1Form"
              :rules="step1Rules"
              ref="step1Form"
              label-width="100px"
              style="margin-top:20px"
            >
              <el-form-item label="培训工种" prop="trainGongZhongId">
                <el-select v-model="step1Form.trainGongZhongId" @change="getNames">
                  <el-option
                    v-for="item in gongZhongs"
                    :key="item.professionId"
                    :label="item.professionName"
                    :value="item.professionId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="培训名称" prop="trainNameId">
                <el-select v-model="step1Form.trainNameId" @change="getClasses">
                  <el-option
                    v-for="item in names"
                    :key="item.trainId"
                    :label="item.trainName"
                    :value="item.trainId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="培训课次" prop="trainClassId">
                <el-select v-model="step1Form.trainClassId">
                  <el-option
                    v-for="item in classes"
                    :key="item.No"
                    :label="item.name"
                    :value="item.No"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <div class="imgCol">
            <button class="btnAddTrainNext pointer" @click="goToStep2">下一步</button>
          </div>
        </div>
        <div v-else>
          <el-row style="margin-top:20px">
            <el-alert :closable="false" center title="详细信息" type="info"></el-alert>
          </el-row>
          <div class="imgCol" style="height:500px">
            <el-form
              :model="step2Form"
              :rules="step2Rules"
              ref="step2Form"
              label-width="110px"
              style="margin-top:20px"
            >
              <el-form-item label="培训人数" prop="requirePopulation">
                <el-input-number v-model="step2Form.requirePopulation" :min="1"></el-input-number>
              </el-form-item>
              <el-form-item label="培训日期" prop="trainDate">
                <el-date-picker
                  @change="correctDate"
                  value-format="yyyy-MM-dd"
                  v-model="step2Form.trainDate"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="培训具体时间" prop="trainTime">
                <el-time-picker
                    default-value="step2Form.trainTime"
                  @change="correctTime"
                  value-format="HH:mm"
                  format="HH:mm"
                  is-range
                  v-model="step2Form.trainTime"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                ></el-time-picker>
              </el-form-item>
              <el-form-item label="培训费用" prop="fee">
                <el-input-number v-model="step2Form.fee" :min="0"></el-input-number>
                <span style="color:#fd034f">￥</span>
              </el-form-item>
              <el-form-item label="联系方式" prop="contact">
                <el-input v-model="step2Form.contact"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="imgCol" style="margin-buttom:20px">
            <button class="btnAddTrainNext pointer" @click="goToStep1">上一步</button>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script>
export default {
  data() {
    var validatePhone = (rule, value, callback) => {
      var pattern = /^1[34578]\d{9}$/;
      if (value === "") {
        callback(new Error("请输入联系方式"));
      } else if (value.length !== 11 || !pattern.test(value)) {
        callback(new Error("手机格式不正确"));
      } else {
        callback();
      }
    };
    return {
      activeStep: 1,

      //step1

      step1Form: {
        //培训工种
        trainGongZhongId: "",
        //培训名称
        trainNameId: "",
        //培训课次
        trainClassId: "",
        //0是保存，1是去下一步
        saveOrnext: 0
      },
      step1Rules: {
        trainGongZhongId: [
          {
            required: true,
            message: "请选择培训工种",
            trigger: "blur"
          }
        ],
        trainNameId: [
          {
            required: true,
            message: "请选择培训名称",
            trigger: "blur"
          }
        ],
        trainClassId: [
          {
            required: true,
            message: "请选择培训课次",
            trigger: "blur"
          }
        ]
      },
      gongZhongs: [],
      names: [],
      classes: [],

      //step2
      step2Form: {
        requirePopulation: 10,
        //数组
        trainDate: [],
        startDate: "",
        endDate: "",

        //数组
        trainTime: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
        startTime: "",
        endTime: "",

        //trainAddress:'',
        fee: 100,
        contact: "",
        //0是保存，1是提交
        saveOrsubmit: 0,
        // trainOthers:'',
        defaultTrainTime: [],
        defaultTrainDate: []
      },
      step2Rules: {
        requirePopulation: [
          {
            required: true,
            message: "请选择培训人数",
            trigger: "blur"
          }
        ],
        trainDate: [
          {
            required: true,
            message: "请选择培训日期",
            trigger: "blur"
          }
        ],
        trainTime: [
          {
            required: true,
            message: "请选择培训具体时间",
            trigger: "blur"
          }
        ],
        trainAddress: [
          {
            required: true,
            message: "请选择培训地点",
            trigger: "blur"
          }
        ],
        fee: [
          {
            required: true,
            message: "请输入培训费用",
            trigger: "blur"
          }
        ],
        contact: [
            {
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          },
          {
            validator: validatePhone,
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    this.getGongZhongs();

    this.save = this.$route.query.save;
    console.log("save==" + this.save);
    if (this.save == 1) {
      this.getSavedTrain();
    }

    var body = document.getElementById("addTrainBox");
    var height = document.documentElement.clientHeight - 120;
    body.style.height = height + "px";

    console.log(height);
  },
  methods: {
    //保存培训
    saveTrain(data) {
      var URL = this.IP + "/train/trainSave";
      console.log(URL);
      console.log(data);
      this.$ajax({
        method: "post",
        url: URL,
        data: data
      })
        .then(response => {
          console.log(response.data);
          var code = response.data.code;
          if (code == 0) {
            this.$message({
              message: response.data.data,
              type: "success"
            });
          } else {
            console.log(response.data.msg);
            this.$message.error(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
          //Toast(error);
        });
    },
    //提交培训
    submitTrain(params) {
      var URL = this.IP + "/train/trainRelease";
      console.log(URL);
      console.log(params);
      this.$ajax({
        method: "put",
        url: URL,
        params: params
      })
        .then(response => {
          console.log(response.data);
          var code = response.data.code;
          if (code == 0) {
            this.$message({
              message: response.data.data,
              type: "success"
            });
            setTimeout(res => {
              this.$router.push({
                path: "/home/checkTrain"
              });
            }, 2000);
          } else {
            console.log(response.data.msg);
            this.$message.error(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
          //Toast(error);
        });
    },
    //获取保存的培训
    getSavedTrain() {
      var URL = this.IP + "/train/trainSaved";
      console.log(URL);
      this.$ajax({
        method: "get",
        url: URL
      })
        .then(response => {
          console.log("保存的培训：");
          console.log(response.data);
          var code = response.data.code;
          var data = response.data.data;
          if (code == 0) {
            this.step1Form.trainGongZhongId = data.professionId;
            if (this.step1Form.trainGongZhongId !== "") {
              console.log("工种id不为空：");
              this.getNames2();
            }
            this.step1Form.trainNameId = data.trainId;
            if (this.step1Form.trainNameId !== "") {
              console.log("培训名id不为空：");
              this.getClasses2();
            }
            this.step1Form.trainClassId = data.trainClassNo;
            this.save == 1;
            this.step1Form.trainGongZhongId = data.professionId;
            this.step1Form.trainNameId = data.trainId;
            this.step1Form.trainClassId = data.trainClassNo;

            this.step2Form.startDate = data.startTime;
            this.step2Form.endDate = data.endTime;
            this.step2Form.startTime = data.startClock;
            this.step2Form.endTime = data.endClock;
            this.step2Form.fee = data.fee;
            this.step2Form.contact = data.contact;
            this.step2Form.requirePopulation = data.requirePopulation;
            this.step2Form.trainDate = [
              new Date(this.step2Form.startDate),
              new Date(this.step2Form.endDate)
            ];
            this.step2Form.trainTime = [
              this.step2Form.startTime,
              this.step2Form.endTime
            ];
          } else {
            console.log(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
          //Toast(error);
        });
    },

    //step1
    goToStep2() {
      this.$refs["step1Form"].validate(valid => {
        if (valid) {
          // console.log('valid');
          // this.step1Form.saveOrnext=1;
          // this.$emit('keepSelection',this.step1Form);

          this.activeStep = 2;
          console.log(this.activeStep);
        } else {
          console.log("error submit!!");
        }
      });
    },
    //获取培训工种
    getGongZhongs() {
      var URL = this.IP + "/visitor/getProfessionInformation";
      console.log(URL);
      this.$ajax({
        method: "get",
        url: URL
      })
        .then(response => {
          console.log(response.data);
          var code = response.data.code;
          if (code == 0) {
            this.gongZhongs = response.data.data.professionInformation;
          } else {
            console.log(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
          //Toast(error);
        });
    },
    //获取培训名和id
    getNames() {
      var URL = this.IP + "/train/getTrainNameAndIdByProfessionId";
      console.log(URL);
      this.$ajax({
        method: "get",
        url: URL,
        params: {
          professionId: this.step1Form.trainGongZhongId
        }
      })
        .then(response => {
          console.log(response.data);
          var code = response.data.code;
          if (code == 0) {
            this.names = response.data.data;
            //this.names=[];
            this.classes = [];
            this.step1Form.trainNameId = "";
            this.step1Form.trainClassId = "";
            // this.classes=[];
            //this.step1Form.trainClassId='';
          } else {
            this.names = [];
            this.classes = [];
            this.step1Form.trainNameId = "";
            this.step1Form.trainClassId = "";
            console.log(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
          //Toast(error);
        });
    },
    getNames2() {
      var URL = this.IP + "/train/getTrainNameAndIdByProfessionId";
      console.log(URL);
      this.$ajax({
        method: "get",
        url: URL,
        params: {
          professionId: this.step1Form.trainGongZhongId
        }
      })
        .then(response => {
          console.log(response.data);
          var code = response.data.code;
          if (code == 0) {
            this.names = response.data.data;
          } else {
            console.log(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
          //Toast(error);
        });
    },
    //获取培训课次名和id
    getClasses() {
      var URL = this.IP + "/train/getTrainClassNameAndNo";
      console.log(URL);
      this.$ajax({
        method: "get",
        url: URL,
        params: {
          trainId: this.step1Form.trainNameId
        }
      })
        .then(response => {
          console.log(response.data);
          var code = response.data.code;
          if (code == 0) {
            this.classes = response.data.data;
            this.step1Form.trainClassId = "";
          } else {
            this.classes = [];
            this.step1Form.trainClassId = "";
            console.log(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
          //Toast(error);
        });
    },
    getClasses2() {
      var URL = this.IP + "/train/getTrainClassNameAndNo";
      console.log(URL);
      this.$ajax({
        method: "get",
        url: URL,
        params: {
          trainId: this.step1Form.trainNameId
        }
      })
        .then(response => {
          console.log(response.data);
          var code = response.data.code;
          if (code == 0) {
            this.classes = response.data.data;
          } else {
            console.log(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
          //Toast(error);
        });
    },

    //step2
    goToStep1() {
      this.activeStep = 1;
    },
    //将培训日期转为后端需要的字段
    correctDate() {
      console.log(this.step2Form.trainDate);
      this.step2Form.startDate = this.step2Form.trainDate[0];
      this.step2Form.endDate = this.step2Form.trainDate[1];
    },
    //将培训具体时间转为后端需要的字段
    correctTime() {
      console.log(this.step2Form.trainTime);
      this.step2Form.startTime = this.step2Form.trainTime[0];
      this.step2Form.endTime = this.step2Form.trainTime[1];
    },

    //为提交整合参数
    submitAll() {
      if (this.activeStep == 1) {
        this.$message({
          message: "请将所有信息补充完整再进行提交",
          type: "warning"
        });
      } else {
        this.$refs["step2Form"].validate(valid => {
          if (valid) {
            var params = {
              professionId: this.step1Form.trainGongZhongId,
              trainId: this.step1Form.trainNameId,
              trainClassNo: this.step1Form.trainClassId,

              startTime: this.step2Form.startDate,
              endTime: this.step2Form.endDate,
              requirePopulation: this.step2Form.requirePopulation,
              fee: this.step2Form.fee,
              contact: this.step2Form.contact,
              startClock: this.step2Form.startTime,
              endClock: this.step2Form.endTime
            };
            console.log(params);
            this.submitTrain(params);
          } else {
            this.$message({
              message: "请将所有信息补充完整再进行提交",
              type: "warning"
            });
          }
        });
      }
    },
    //为保存整合参数
    saveAll() {
      var data = {
        professionId: this.step1Form.trainGongZhongId,
        trainId: this.step1Form.trainNameId,
        trainClassNo: this.step1Form.trainClassId,

        startTime: this.step2Form.startDate,
        endTime: this.step2Form.endDate,
        requirePopulation: this.step2Form.requirePopulation,
        fee: this.step2Form.fee,
        contact: this.step2Form.contact,
        startClock: this.step2Form.startTime,
        endClock: this.step2Form.endTime
      };
      console.log(data);
      this.saveTrain(data);
    }
  }
};
</script>
<style>
#addTrainBox {
  /* height:600px; */
  background-color: #fff;
  margin: 15px;
  border-radius: 5px;
}
#btnFoot {
  position: fixed;
  bottom: 100px;
  left: 45%;
}
.el-header,
.el-main,
.el-footer,
.el-aside {
  padding: 0px;
}

.end {
  display: flex;
  justify-content: flex-end;
}
.imgCol {
  display: flex;
  justify-content: center;
  align-items: center;
}
.btnAddTrainNext {
  width: 400px;
  height: 40px;
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
  border-style: none;

  border-radius: 5px;
}
.pointer {
  cursor: pointer;
}
</style>